import React from 'react';

export default (options = {}) => {
  const { Component, ref } = options;
  class Preview extends React.Component {
    state = {
      visible: false,
      value: undefined,
    };

    show = () => {
      const { editor } = this.props;
      this.setState({
        visible: true,
        value: editor.value.toJS(),
      });
    };

    close = () => {
      this.setState({
        visible: false,
      });
    };

    render() {
      const { visible, value } = this.state;
      return (
        <Component
          value={value} visible={visible}
          onClose={this.close}
        />
      );
    }
  }
  return {
    commands: {
      preview: () => {
        if (ref.current) {
          ref.current.show();
        }
      },
    },
    renderEditor: (props, editor, next) => {
      const children = next();
      return (
        <>
          {children}
          <Preview ref={ref} editor={editor} />
        </>
      );
    },
  };
};
